ggplot ?Cela dépendent en général du type de variable (qualitative ou quantitative) et du nombre de variables.
knitr::include_graphics("graphique1.jpg")
knitr::include_graphics("graphique2.jpg",
auto_pdf = getOption("knitr.graphics.auto_pdf", FALSE))
ggplot 2Voici plusieurs commandes que nous utiliserons avant de présenter les graphiques :
%>% : pipeline / pipe operator / tuyau. Il indique juste une succession d’opération. “j’applique ce qui viens après le symbole à ce qui est à sa droite” ==> son raccourci ; Ctrl+Shift+M (Windows), Cmd+Shift+M (Mac)
select : selectionner des variables
filter : selectionner des observations
mutate : recoder et créer de nouvelles variables
class : connaître le type d’une variable
as.numeric / as.factor : changer le type d’une variable. as.factor : La fonction factor permet de créer une variable qualitative ou categorielle ou factorielle, à partir d’une autre variable.
if_else : recoder des variables avec des conditions
group_by : regrouper
En général pour visualiser des données, on doit nettoyer la base de données en fonction de ce que nous souhaitons raconter et présénter.
Cela vaut autant pour les données numériques que textuelles (pre-processing)!
===============================================
rm(list = ls())
#install.packages("tidyverse")
library(haven) #importation de données sous forme dta
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ ggplot2 3.3.5 ✓ purrr 0.3.4
## ✓ tibble 3.1.4 ✓ dplyr 1.0.7
## ✓ tidyr 1.1.3 ✓ stringr 1.4.0
## ✓ readr 2.0.0 ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
#library(scales)
covid <- read_dta("Covid_2.dta")
quality_governance <- read.csv("Quality_Governance.csv")
ggplot2ggplot() :?ggplot2
ggplot() permet de lier des données à une représentation graphique.Vous pouvez construire des graphiques à partir de mêmes composants :
ggplot(data = covid)
ggplot(data = covid,
mapping = aes(x = age , y = semaines))
* Pour ajouter plus d’esthétisme et les valeurs, on ajoute des propriétés visuelles avec la commande aes() (aesthetic) à la géométrie pour : + la taille (size), + la position (position), + la transparence (alpha), + le remplissage (fill), + la forme (shape), + la couleur (color) et + les emplacements de vos variables dépendante et indépendante.
a <- ggplot(data = covid, mapping = aes(x = semaines)) +
geom_density()
a
#knitr::include_graphics(" composants-de-base_ggplot.jpg")
#knitr::include_graphics("composants-avances_ggplot.jpg")
#knitr::include_graphics("graphique2.jpg")
# Pour la couleur :
b <- ggplot(data = covid, mapping = aes(x = semaines)) +
geom_density(color = "blue")
b
# avec un histogramme :
b1 <- ggplot(data = covid, mapping = aes(x = pr_med_info_0a10)) +
geom_bar(aes(fill = "red"))
b1
## Don't know how to automatically pick scale for object of type haven_labelled/vctrs_vctr/double. Defaulting to continuous.
a <- ggplot(data = covid, mapping = aes(x = semaines)) +
geom_density(color = "blue")
a
# On peut représenter la distribution des avis du nombre des semaine de quarantaine par genre :
a1 <- ggplot(data = covid, mapping = aes(x = semaines, fill = as.factor(femme))) +
geom_density()
a1
# On peut aussi modifier l'ombrage des distributions :
a2 <- ggplot(data = covid, mapping = aes(x = semaines, fill = as.factor(femme))) +
geom_density(alpha = 0.4)
a2
# On peut créer deux graphiques distincts qui présentent la distribution des avis sur le nombre de semaines de quarantaine par genre :
a3 <- ggplot(data = covid, mapping = aes(x = semaines, fill = as.factor(femme))) +
geom_density() +
facet_wrap(~as.factor(femme))
a3
# Finalement, on peut ajouter les étiquettes :
a5 <- ggplot(data = covid, mapping = aes(x = semaines, fill = as.factor(femme))) +
geom_density(alpha = 0.7) +
facet_wrap(~as.factor(femme)) +
scale_fill_discrete(name = "Genre") +
scale_x_continuous(name = "Nombre de semaines de quarantaine",
breaks = seq(0,20, by = 2)) +
labs(title = "Distribution des avis sur la durée du confinement en fonction du genre",
subtitle = "Données COVID-19 France",
x = "Nombres de semaines de confinement",
y = "Densité",
caption = "Graphique par Anne Imouza")
a5
c <- ggplot(data = covid, mapping = aes(x = semaines, y = age, color = as.factor(femme))) +
geom_point()
c
#on modifie les variables sexe (femme) et idéologie pour qu'elles soient des variables catégorielles, et non continues.
d <- ggplot(data = covid, mapping = aes(x = semaines, y = age, shape = as.factor(femme))) +
geom_point()
d
# scale
e <- c +
scale_color_discrete(name = "Genre",
labels = c("Femme", "Homme")) +
scale_x_continuous(name = "Nombre de semaines",
breaks = seq(0,20, by = 2)) +
scale_y_continuous(name = "Age",
breaks = seq(0, 87, by = 6))
e
# labs
f <- e +
labs(title = "Age en fonction des avis sur la durée de semaines de quarantaine",
subtitle = "Données COVID-19 France",
x = "Semaines de quarantaine",
y = "Age",
caption = "Graphique par Anne Imouza")
f
quality_governance <- read.csv("Quality_Governance.csv")
ggplot(quality_governance) +
geom_boxplot(aes(x = region, y = femmes_travail)) +
geom_point(aes(x = region, y = femmes_travail, color = region)) +
theme(axis.text.x = element_text(colour = "black", angle = 25))
## Warning: Removed 17 rows containing non-finite values (stat_boxplot).
## Warning: Removed 17 rows containing missing values (geom_point).
# On veut seulement voir pour les régions suivantes : afrique_nord_moyen_orient, asie_sud, caraibes, amerique_latine et europe_ouest_amerique_nord
ggplot(quality_governance) +
geom_boxplot(aes(x = region, y = femmes_travail)) +
geom_point(aes(x = region, y = femmes_travail, color = region)) +
theme(axis.text.x = element_text(colour = "black", angle = 10)) +
scale_x_discrete("Regions", limits = c("afrique_nord_moyen_orient", "asie_sud","caraibes", "amerique_latine", "europe_ouest_amerique_nord"))
## Warning: Removed 106 rows containing missing values (stat_boxplot).
## Warning: Removed 8 rows containing non-finite values (stat_boxplot).
## Warning: Removed 114 rows containing missing values (geom_point).
*On peut utiliser plusieurs thèmes pour présenter nos résultats : + r + theme_bw() : fond blanc avec des lignes de quadrillage + r + theme_gray() : Fond gris + r + theme_dark() : Noir pour les contrastes + r + theme_classic() + r + theme_light() + r + theme_linedraw() + r + theme_minimal(): thème minimal + r + theme_void() : Thème vide
Pour plus d’information : https://ggplot2.tidyverse.org/reference/theme.html
#Notre graphique de densité univarié :
g <- a5 +
theme_dark()
g
#Notre grahique multivarié
h <- e + theme_minimal()
h
i <- ggplot(data = covid, mapping = aes(x = semaines, y = age)) +
geom_point() +
geom_smooth(aes(color = as.factor(femme)), method = "lm")
i
## `geom_smooth()` using formula 'y ~ x'
# Enregistrer un graphique :
ggsave(filename = "graphique_regression_lineaire.png", plot = i, width = 9, height = 6)
## `geom_smooth()` using formula 'y ~ x'
Exercices
quality_governance <- read.csv("Quality_Governance.csv")
femmes_travail qui se trouve dans la base de données quality_governance. Utilisez la fonction summary :summary(quality_governance$femmes_travail)
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## 8.133 39.319 43.828 41.036 47.108 54.976 17
quality_gov_aqui ne contient pas les variables suivantes : taux_dep, renouvelable et terre_arable. utilisez la fonction %>% et filter.quality_gov_a <- quality_governance %>%
select(-taux_dep, -renouvelable, -terre_arable)
fecondité.graph_fec <- ggplot(quality_gov_a, aes(x=fecondite)) +
geom_bar(aes(fill = "orange"))
graph_fec
## Warning: Removed 9 rows containing non-finite values (stat_count).
pib_habitant (x) et acces_internet (y).graph_bi <- ggplot(quality_gov_a, aes(x= pib_habitant, y = acces_internet)) +
geom_point()
graph_bi
## Warning: Removed 12 rows containing missing values (geom_point).
graph_bi <- ggplot(quality_gov_a, aes(x= pib_habitant, y = acces_internet, color = region)) +
geom_point()
graph_bi
## Warning: Removed 12 rows containing missing values (geom_point).
scaleset un thème. 9.1 Limitez l’intervalle du PIB par habitant de 0 à 30000$.graph_bi <- ggplot(quality_gov_a, aes(x= pib_habitant, y = acces_internet, color = region)) +
geom_point() +
scale_x_continuous("PIB par habitant",
limits = c(0,30000)) +
scale_y_continuous("Accès à l'internet") +
scale_color_discrete("Régions")
graph_bi
## Warning: Removed 41 rows containing missing values (geom_point).
9.2 Créez un graphique en fonction du genre (
facet_wrap).
#on veut enlever les NA. une solution possible :
quality_gov_a <- quality_gov_a %>%
drop_na(fecondite)
graph_bi_a <- graph_bi +
facet_wrap(~fecondite)
graph_bi_a
## Warning: Removed 41 rows containing missing values (geom_point).
En utilisant la commande labs, ajoutez un titre, un sous titre, renommez les variables et indiquez votre prénom et nom.
graph_bi_b <- graph_bi +
labs(title = "Accès à l'internet en fonction du PIB par habitant et de la fécondité par région",
subtitle = "Données du Quality of governance",
x = "Pib par habitant",
y = "Accès à l'internet",
caption = "Graphique par Anne Imouza")
graph_bi_b
## Warning: Removed 41 rows containing missing values (geom_point).
pib_habitant et acces_internet en fonction de la fécondité :graph_ai <- ggplot(quality_gov_a, aes(x= pib_habitant, y = acces_internet, color = as.factor(fecondite))) +
geom_point() +
scale_x_continuous("PIB par habitant",
limits = c(0,30000)) +
scale_y_continuous("Accès à l'internet") +
scale_color_discrete("Fecondité") +
geom_smooth(method = "lm")
graph_ai
## `geom_smooth()` using formula 'y ~ x'
## Warning: Removed 36 rows containing non-finite values (stat_smooth).
## Warning: Removed 36 rows containing missing values (geom_point).
ggsave(filename = "graphique_regression_lineaire2.png", plot = graph_ai, width = 9, height = 6)
## `geom_smooth()` using formula 'y ~ x'
## Warning: Removed 36 rows containing non-finite values (stat_smooth).
## Warning: Removed 36 rows containing missing values (geom_point).